<?php
namespace app\admin\model;

use support\bootstrap\Log;
use support\util\TreeArray;
use support\Model;

class Menu extends Model
{
    protected $fillable = ['type', 'pid', 'pids', 'title', 'rule', 'icon', 'condition', 'weigh', 'status', 'remark', 'target'];

    protected $visible = [
        'id',
        'pid',
        'pids',
        'type',
        'title',
        'icon',
        'weigh',
        'child',
        'rule',
        'status',
        'condition',
        'target'
    ];

    protected $appends = [
    ];

    protected static function booted(){
        static::deleted(function ($row) {
            // 删除相关子集
            self::whereRaw("FIND_IN_SET(" . $row->id . ", `pids`)")->delete();
        });
    }

    /**
     * 父级菜单
     */
    public function parentmenu()
    {
        return $this->hasOne(self::class ,'id', 'pid');
    }

    public function roles()
    {
        return $this->belongsToMany(Role::class, 'role_menu_access', 'menu_id', 'role_id');
    }

    public static function getTypeList()
    {
        return ['menu' => '菜单', 'btn' => '按钮'];
    }

    public static function getTragetList()
    {
        return ['_iframe' => '本框架打开', '_blank' => '新窗口打开'];
    }

    public static function getStatusList()
    {
        return ['normal' => '正常', 'disable' => '禁用', 'hidden' => '隐藏'];
    }

    public static function getTreeSelect()
    {
        $tree = self::getTree();
        $list = $tree->getTreeArray(0);
        return array_merge([['id' => 0, 'title' => '顶级菜单', 'pid' => 0]],$tree->getTreeList($list, 'title'));
    }

    public static function getTree()
    {
        $list = self::query()->where('type', 'menu')
            ->orderByDesc('weigh')
            ->get();
        $tree = TreeArray::instance();
        $tree->init($list->toArray());
        return $tree;
    }

    public function scopeSearch($query, $where = []) {
        return $query;
    }
}
